package org.roger.search;

import java.io.IOException;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TermQuery;
import org.roger.bean.IndexModel;

/**
 * 多条件搜索
 */
public class MultiSearch extends LuceneSearchBase{
	
	private IndexModel[] model;
	
	public MultiSearch(IndexModel[] model){
		this.model = model;
	}

	@Override
	public Query getSearchQuery() {
		BooleanQuery bq = new BooleanQuery(); 
		
		for(int i = 0; i < model.length; i++){
			BooleanQuery tmpBQ = new BooleanQuery();
			if(null != model[i].getPath())
				tmpBQ.add(new TermQuery((new Term("path",model[i].getPath()))),model[i].getOpts()[0]);
			if(null != model[i].getModified())
				tmpBQ.add(new TermQuery((new Term("modified",model[i].getModified()))),model[i].getOpts()[1]);
			if(null != model[i].getContents())
				tmpBQ.add(new TermQuery((new Term("contents",model[i].getContents()))),model[i].getOpts()[2]);
			bq.add(tmpBQ, BooleanClause.Occur.SHOULD);
		}
		return bq;
	}
	
	public static void main(String[] args) {
		IndexModel[] models = new IndexModel[3];
		
		IndexModel model1 = new IndexModel();
		//model1.setPath("file");
		model1.setModified(null);
		model1.setContents("freshness");
		BooleanClause.Occur[] opts1 = new BooleanClause.Occur[3];
		opts1[0] = BooleanClause.Occur.MUST;
		opts1[1] = BooleanClause.Occur.MUST;
		opts1[2] = BooleanClause.Occur.MUST;
		model1.setOpts(opts1);
		models[0] = model1;
		
		IndexModel model2 = new IndexModel();
		model2.setPath("file");
		model2.setModified(null);
		model2.setContents("human");
		BooleanClause.Occur[] opts2 = new BooleanClause.Occur[3];
		opts2[0] = BooleanClause.Occur.MUST;
		opts2[1] = BooleanClause.Occur.MUST;
		opts2[2] = BooleanClause.Occur.MUST;
		model2.setOpts(opts2);
		models[1] = model2;
		
		IndexModel model3 = new IndexModel();
//		model3.setPath("file");
		model3.setModified(null);
		model3.setContents("optimism");
		BooleanClause.Occur[] opts3 = new BooleanClause.Occur[3];
		opts3[0] = BooleanClause.Occur.MUST;
		opts3[1] = BooleanClause.Occur.MUST;
		opts3[2] = BooleanClause.Occur.MUST;
		model3.setOpts(opts3);
		models[2] = model3;
		
		MultiSearch search = new MultiSearch(models);
		try {
			search.search("D:/index");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Filter getFilter() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Sort getSort() {
		// TODO Auto-generated method stub
		return null;
	}

	

}
